package com.coocaa.aries.jmeter.service.impl;


import com.coocaa.aries.core.tool.InstanceUtil;
import com.coocaa.aries.jmeter.biz.impl.ExtTestCaseBizImpl;
import com.coocaa.aries.jmeter.entity.ExtTestCaseInfoEntity;
import com.coocaa.aries.jmeter.service.IRunTimeProcessService;
import com.coocaa.aries.jmeter.thread.TestCaseExecThread;
import com.coocaa.aries.jmeter.yml.JmeterProperties;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.*;

/**
 * @author : bijiahao
 * @date : 2019/4/1.
 * @description:
 */
@Service
public class RunTimeProcessServiceImpl implements IRunTimeProcessService {

    private Map<Integer, Process> processMap = InstanceUtil.newHashMap(200);

    private ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
            .setNameFormat("handle-RunTimeTask-pool").build();

    private ExecutorService poolExecutor = Executors.newSingleThreadExecutor();

    private ExecutorService streamGobblerExecutor = new ThreadPoolExecutor(4, 9,
            120L, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>(), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());

    @Autowired
    private JmeterProperties jmeterProperties;
    @Autowired
    private ExtTestCaseBizImpl extTestCaseBiz;

    /**
     *
     */

    @Override
    public void exec(ExtTestCaseInfoEntity entity) throws Exception {
        poolExecutor.execute(new TestCaseExecThread(entity, jmeterProperties, extTestCaseBiz, processMap, streamGobblerExecutor));
    }

    @Override
    public void removeProcess(Integer id) {
        Process process = processMap.get(id);
        if (null != process) {
            process.destroy();
        }
        processMap.remove(id);
    }
}
